﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace EMall.Middlewares
{
    public class PermissionCheckMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;
        public PermissionCheckMiddleware(RequestDelegate next,
            ILogger<AuthorizationMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }
        public async Task Invoke(HttpContext context)
        {
            ArgumentNullException.ThrowIfNull(context);
            var endpoint = context.GetEndpoint();
            var authorizeData = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>() ?? Array.Empty<IAuthorizeData>();
            if (!authorizeData.Any())
            {
                await _next(context);
                return;
            }
            if (endpoint?.Metadata.GetMetadata<IAllowAnonymous>() != null)
            {
                await _next(context);
                return;
            }
            var checkPass = true;
            if (checkPass)
            {
                await _next(context);
                return;
            }
            await context.ForbidAsync();
        }
    }
    public static class PermissionCheckAppBuilderExtensions
    {
        public static IApplicationBuilder UsePermissionCheck(this IApplicationBuilder app)
        {
            ArgumentNullException.ThrowIfNull(app);
            //app.UseSerilogRequestLogging();
            return app.UseMiddleware<PermissionCheckMiddleware>();
        }
    }
}



//public class PermissionAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
//{
//    public const string SchemeName = "PermissionAuth";
//    public PermissionAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder) : base(options, logger, encoder)
//    {
//    }
//    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
//    {
//        var principal = new ClaimsPrincipal();
//        principal.AddIdentity(new ClaimsIdentity(
//            new[]
//            {
//                    new Claim("Manager", "yes"),
//                    new Claim(ClaimTypes.Role, "Administrator"),
//                    new Claim(ClaimTypes.NameIdentifier, "John")
//            },
//            Scheme.Name));

//        return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(
//            principal,
//            new AuthenticationProperties(),
//            Scheme.Name)));
//    }
//}
//public class PermissionAuthorizationRequirement : AuthorizationHandler<PermissionAuthorizationRequirement>, IAuthorizationRequirement
//{
//    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionAuthorizationRequirement requirement)
//    {
//        if (context.User != null)
//        {
//            var found = false;

//            //foreach (var role in requirement.AllowedRoles)
//            //{
//            //    if (context.User.IsInRole(role))
//            //    {
//            //        found = true;
//            //        break;
//            //    }
//            //}

//            if (found)
//            {
//                context.Succeed(requirement);
//            }
//        }
//        return Task.CompletedTask;
//    }
//}